/**
 * Time：2024.04.28
 * Content：condition_variable使用场景
 * Author：Qian You
 */
#include <iostream>
#include <bits/stdc++.h>
// 头文件
#include <thread>
using namespace std;

queue<int> q;
condition_variable g_cv;
mutex mtx;

void Producer()
{
    for (int i = 0; i < 10; i++)
    {
        unique_lock<mutex> lock(mtx);
        q.push(i);
        // 通知消费者来取
        g_cv.notify_one();
        cout << "Producer: " << i << endl;
    }
    this_thread::sleep_for(chrono::microseconds(1000));
}

void Consumer()
{
    while (1)
    {
        unique_lock<mutex> lock(mtx);
        // 任务队列为空则等待
        g_cv.wait(
            lock, []()
            { return !q.empty(); });
        int value = q.front();
        q.pop();
        cout << "Consumer: " << value << endl;
    }
}

int main()
{
    thread t1(Producer);
    thread t2(Consumer);
    t1.join();
    t2.join();
    return 0;
}